use jsonrpsee::types::ErrorObjectOwned;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;

use aspect_codec::{Codec, CodecError};

#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HexBuf(#[serde_as(as = "serde_with::hex::Hex")] pub Vec<u8>);

impl HexBuf {
    pub fn try_from_codec<T: Codec>(v: &T) -> Result<Self, CodecError> {
        Ok(Self(aspect_codec::encode_to_vec(v)?))
    }

    pub fn try_into_codec<T: Codec>(&self) -> Result<T, CodecError> {
        Ok(aspect_codec::decode(&self.0)?)
    }
}

impl Into<Vec<u8>> for HexBuf {
    fn into(self) -> Vec<u8> {
        self.0
    }
}

impl From<Vec<u8>> for HexBuf {
    fn from(value: Vec<u8>) -> Self {
        Self(value)
    }
}

pub fn conv_device_err(e: aspect_ident::errors::Error) -> ErrorObjectOwned {
    ErrorObjectOwned::owned::<()>(42, format!("{e}"), None)
}

pub fn conv_codec_err(_: aspect_codec::CodecError) -> ErrorObjectOwned {
    ErrorObjectOwned::owned::<()>(44, "malformed encoded object".to_owned(), None)
}

pub fn conv_db_err(_: aspect_db_common::errors::Error) -> ErrorObjectOwned {
    ErrorObjectOwned::owned::<()>(45, "database errror".to_owned(), None)
}
